﻿using System;
using System.Text.RegularExpressions;

namespace SQLDataTransferer.Model
{
    public class SqlInstance : IComparable<SqlInstance>
    {
        #region Constructor(s)

        public SqlInstance(string serverName = null, string instanceName = null)
        {
            this.ServerName = serverName;
            this.InstanceName = instanceName;
        }

        #endregion

        #region Properties

        public string ServerName { get; set; }

        public string InstanceName { get; set; }

        public string FullName
        {
            get
            {
                if (string.IsNullOrEmpty(this.ServerName) && string.IsNullOrEmpty(this.InstanceName))
                    return string.Empty;

                if (string.IsNullOrEmpty(this.ServerName) && !string.IsNullOrEmpty(this.InstanceName))
                    return this.InstanceName.ToUpper();

                if (!string.IsNullOrEmpty(this.ServerName) && string.IsNullOrEmpty(this.InstanceName))
                    return this.ServerName.ToUpper();

                return string.Format(@"{0}\{1}", this.ServerName, this.InstanceName).ToUpper();
            }
        }

        #endregion

        #region Methods

        public static SqlInstance Parse(string value)
        {
            if (string.IsNullOrEmpty(value))
                return null;

            // if single backslash, make sure its doubledup so we can split on it
            value = Regex.Escape(value);

            // try to split the provided value
            string[] splitted = Regex.Split(value, @"\\");

            // if character not found, the split will return 1 result
            if (splitted.Length == 1)
                return new SqlInstance(splitted[0], null);

            // if there are more than 1 characters foudn the splitted values will contain empty entries, 
            // and should no be used to create a new instance of the SQLInstance type (use first and last item)
            return new SqlInstance(splitted[0], splitted[splitted.Length - 1]);
        }

        #endregion

        #region Overrides

        public override string ToString()
        {
            return this.FullName;
        }

        #endregion

        #region IComparable<SqlInstance> Members

        public int CompareTo(SqlInstance other)
        {
            if (other != null)
                return this.FullName.ToLower().CompareTo(other.FullName.ToLower());
            return 0;
        }

        #endregion
    }
}
